package com.example.okhttp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private static final String TAG ="" ;
    OkHttpClient okHttpClient;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        //get
          okHttpClient=new OkHttpClient();

    }

    public void get(View view) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                Request request= new Request.Builder().url("https://www.baidu.com/").build();
                //准备好请求得对象
                Call call = okHttpClient.newCall(request);
                try {
                Response response=call.execute();
                    Log.d(TAG,""+response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();


                }
            }
        }).start();



    }

    //get异步请求
    public void getyibu(View view) {
        Request request= new Request.Builder().url("https://www.httpbin.org/get?a=1&b=2").build();
      //准备好请求的CaLL对象
        Call call=okHttpClient.newCall(request);
        //异步请求
        call.enqueue(new Callback() {
            //请求失败
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            //请求成功
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
     if (response.isSuccessful()){

    Log.d(TAG,""+response.body().toString());
}

            }
        });
    }



    public void post(View view) {



        new Thread(new Runnable() {
            @Override
            public void run() {
                                //创建 FormBody得post请求
                FormBody formBody = new FormBody.Builder().add("a", "1").add("b", "2").build();
                Request request = new Request.Builder().url("https://www.httpbin.org/post").post(formBody).build();
                //准备好请求得对象
                Call call = okHttpClient.newCall(request);
                try {
                    Response response = call.execute();
                    Log.d(TAG, "" + response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();

                }


            }
        }).start();
            }



}